<?php
/**
 * Created by PhpStorm.
 * User: inhere
 * Date: 2016/03/9
 * Time: 15:30
 */

namespace app\handlers;

use Slim;
use slimExt\base\Collection;
use slimExt\DataCollector;
use app\extensions\MderPage;
use Symfony\Component\Yaml\Dumper;
use slimExt\base\Request;

/**
 * Class DefaultHandler
 * @package app\handlers
 *
 */
class DefaultHandler extends AbstractHandler
{
    /**
     * @param Request $req
     * @return string
     */
    protected function handleInputs(Request $req)
    {
        $page = $req->getTrimmed('page');
        $setting = $req->getTrimmed('setting');

        $settings = DataCollector::parseYaml($setting);

        // check page string
        if ( !MderPage::checkPath($page) ) {
            $this->error = "page path format error! Page: [$page]";

            return false;
        }

        // check or add some setting
        $settings['author'] = Slim::$app->user['username'];
        if ( empty($settings['publishTime']) ) {
            $settings['publishTime'] = date('Y-m-d H:i:s');
        }

        if ( empty($settings['route']) ) {
            $settings['route'] = $this->pager->getPageUrl(true);
        }

        $dumper = new Dumper();
        $setting = $dumper->dump($settings, 1, 0);

        $content = $req->getTrimmed('content');
        $text = "{###\n" . $setting . "\n###}\n\n" . $content;

        return [$text, $settings];
    }

}